﻿using Application.Common.Interface;
using Domain.Model;
using Microsoft.EntityFrameworkCore;

namespace Core.Persistence.Repository
{
    public class SiteMapRepository : ISiteMapRepository
    {
        private readonly WebScraperDbContext dbContext;
        public SiteMapRepository(WebScraperDbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public async Task AddAsync(SiteMap siteMap)
        {
            await dbContext.siteMap.AddAsync(siteMap);
            await dbContext.SaveChangesAsync();
        }
        public async Task<SiteMap?> GetAsync(int Id)
        {
            return await dbContext.siteMap.FirstOrDefaultAsync(s => s.Id == Id);
        }

        public async Task<IEnumerable<SiteMap>> GetAllAsync()
        {
            return await dbContext.siteMap.ToListAsync();
        }
        public async Task<IEnumerable<SiteMap>> GetSearchByIDDomain(string text)
        {
            return await dbContext.siteMap.Where(s => s.Name.Contains(text) || s.Domain.Contains(text)).ToListAsync();
        }
        public async Task UpdateAsync(SiteMap siteMap)
        {
            dbContext.Update(siteMap);
            await dbContext.SaveChangesAsync();
        }

        public async Task DeleteAsync(int Id)
        {
            var dels = await dbContext.selector.Where(s => s.SiteMapId == Id).ToListAsync();
            dbContext.RemoveRange(dels);
            dbContext.siteMap.Remove(new() { Id = Id });
            await dbContext.SaveChangesAsync();
        }
    }
}
